<template>
  <div class="p-3 bg-white border-t">
    <!-- 文件 URL 输入对话框 -->
    <el-dialog v-model="showFileDialog" title="添加文件" width="500px">
      <el-input v-model="fileUrl" type="textarea" :rows="3" placeholder="请输入文件URL..." />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showFileDialog = false">取消</el-button>
          <el-button type="primary" @click="handleAddFile">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 流式/非流式选择按钮 -->
    <div class="mb-3 flex items-center gap-2">
      <el-radio-group v-model="streamType" size="small">
        <el-radio-button :label="1" @click="unShow">流式</el-radio-button>
        <el-radio-button :label="2" @click="unShow">结构化供应商数据</el-radio-button>
        <el-radio-button :label="3" @click="show">其他选项</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 文件显示区域 -->
    <div v-if="currentFileUrl" class="mb-2 p-2 bg-gray-50 rounded flex items-center justify-between">
      <div class="text-sm text-gray-600 truncate flex-1">
        已添加文件: {{ currentFileUrl }}
      </div>
      <el-button type="danger" link @click="currentFileUrl = ''">
        <el-icon>
          <Delete />
        </el-icon>
      </el-button>
    </div>

    <div class="flex items-center gap-2">
      <!-- 删除聊天记录按钮 -->
      <el-button type="danger" :icon="Delete" circle @click="handleClearHistory" title="清空聊天记录" />

      <!-- 消息输入框（包含附件按钮） -->
      <div class="relative flex-1">
        <el-autocomplete v-model="inputText" :fetch-suggestions="querySearch" type="text" :rows="1"
          placeholder="我目前支持的功能有'查询模型信息'、'查询app信息'、'查询供应商信息'，请输入..." @keyup.enter.prevent="handleSend"
          :trigger-on-focus="false" class="custom-input" popper-class="autocomplete-popper">
          <!-- 添加自定义建议项渲染，实现高亮 -->
          <template #default="{ item }">
            <div v-html="highlightMatch(item.value, inputText)"></div>
          </template>

          <template #suffix>
            <el-button type="primary" :icon="Plus" circle @click="showFileDialog = true"
              class="absolute right-2 top-1/2 transform -translate-y-1/2" size="small" />
          </template>
        </el-autocomplete>
      </div>

      <!-- 发送按钮 -->
      <el-button type="primary" :loading="isLoading" @click="handleSend" class="flex-shrink-0">
        <el-icon>
          <Position />
        </el-icon>
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Position, Plus, Delete } from '@element-plus/icons-vue'
import { useChatStore } from '../stores/chat'
import { storeToRefs } from 'pinia'
import { ElMessage, ElMessageBox } from 'element-plus'
import { debounce } from 'lodash-es';

const chatStore = useChatStore()
const inputText = ref('')
const isLoading = computed(() => chatStore.isLoading)

const { formDataIsShow } = storeToRefs(chatStore)

// 文件相关状态
const showFileDialog = ref(false)
const fileUrl = ref('')
const currentFileUrl = ref('')

// 流式/非流式选择状态（改为数字）
const streamType = ref(1) // 默认选中第一个选项

// 高亮匹配文本的方法
const highlightMatch = (text: string, query: string) => {
  if (!query || !text) return text;

  // 转义特殊字符，防止正则表达式错误
  const escapedQuery = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  const regex = new RegExp(`(${escapedQuery})`, 'gi');
  return text.replace(regex, '<span class="highlight-match">$1</span>');
};

// 公共请求参数
const getBaseRequestParams = (contents = []) => ({
  appId: "1889570169345757186",
  userId: 31,
  contents,
  knowledgeIds: [],
  isStream: streamType.value
})

const querySearch = async (queryString: string, cb: any) => {
  try {
    const res = await chatStore.getSuggestions(queryString);

    console.log("输入框发生变化", queryString);
    console.log("返回值为", res);

    if (Array.isArray(res)) {
      cb(res.map(item => ({
        value: item.content,
        // 原始内容也保留，用于高亮显示
        rawValue: item.content
      })));
    } else {
      console.error("返回值不是数组:", res);
      cb([]);
    }
  } catch (error) {
    console.error("获取建议失败:", error);
    cb([]);
  }
};

// 处理清空聊天记录
const handleClearHistory = () => {
  ElMessageBox.confirm('确定要清空所有聊天记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    chatStore.clearHistory2(getBaseRequestParams())
    ElMessage.success('聊天记录已清空')
  }).catch(() => {
    // 用户取消操作
  })
}

// 处理添加文件
const handleAddFile = () => {
  if (fileUrl.value.trim()) {
    currentFileUrl.value = fileUrl.value.trim()
    fileUrl.value = ''
  }
  showFileDialog.value = false
}

const show = () => {
  console.log('show')
  formDataIsShow.value = true
}
const unShow = () => {
  console.log('show')
  formDataIsShow.value = false
}

// 处理发送消息
const handleSend = () => {
  if (!inputText.value.trim() && !currentFileUrl.value) return

  const contents = []

  // 添加文本内容
  if (inputText.value.trim()) {
    contents.push({
      content: inputText.value.trim(),
      contentType: "text"
    })
  }

  // 添加文件内容
  if (currentFileUrl.value) {
    contents.push({
      content: `${currentFileUrl.value}`,
      contentType: "fileUrl"
    })
  }

  // 使用公共参数构建请求
  chatStore.sendMessage(getBaseRequestParams(contents))

  // 清空输入
  inputText.value = ''
  currentFileUrl.value = ''
}

// 第一次加载页面的获取历史记录
const getHistory = () => {
  chatStore.loadHistory(getBaseRequestParams())
    .then((res) => {
      console.log(res)
    })
}

// 在组件挂载时加载历史记录
onMounted(() => {
  //先清空历史记录
  chatStore.clearHistory()
  getHistory()
})
</script>

<style scoped>
.custom-input :deep(.el-input__wrapper) {
  background-color: var(--el-fill-color-blank);
  box-shadow: none;
  padding-right: 40px;
  /* 为按钮留出空间 */
}

.custom-input :deep(.el-input__inner) {
  height: 32px;
  line-height: 32px;
}

.dialog-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>

<style>
/* 高亮匹配文本的样式 */
.highlight-match {
  color: var(--el-color-primary);
  font-weight: bold;
}

/* 自定义下拉框样式 */
.autocomplete-popper .el-autocomplete__suggestion {
  padding: 8px 12px;
}

.autocomplete-popper .el-autocomplete__suggestion.highlighted {
  background-color: var(--el-color-primary-light-9);
}
</style>